using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace Sora.Tools.TextureSetting
{
    public class TextureSettingWindow : EditorWindow
    {
        #region constructor

        #endregion


        #region event
        #endregion


        #region property
        public VisualElement root { get; private set; }

        #endregion


        #region engine method
        private void OnDestroy()
        {
            EditorPrefs.SetBool("texture setting open", false);
        }
        #endregion

        #region public method
        #endregion


        #region protected method
        #endregion


        #region private method
        private void Init()
        {
            root = rootVisualElement;
            GetVisualTree("TextureSettingWindow").CloneTree(root);

            var textureType = root.Q<EnumField>("texture type");
            var wrapMode = root.Q<EnumField>("wrap mode");
            var filterMode = root.Q<EnumField>("filter mode");
            var anisoLevel = root.Q<Slider>("aniso level");
            var platform = root.Q<EnumField>("platform");
            var forceOverride = root.Q<Toggle>("force override");
            var maxSize = root.Q<EnumField>("max size");
            var resizeAlgorithm = root.Q<EnumField>("resize algorithm");
            var format = root.Q<EnumField>("format");
            var startButton = root.Q<Button>("start");

#if UNITY_2020
            startButton.clicked += StartCallback;
#else
            startButton.clickable.clicked += StartCallback;
#endif

            void StartCallback()
            {
                var textures = Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
                if (textures != null)
                {
                    if (textures.Length < 1)
                    {
                        ShowNotification(new GUIContent("找不到图片!"));
                        return;
                    }
                }
                else
                {
                    ShowNotification(new GUIContent("请选中图片或路径!"));
                    return;
                }
                var index = 1;
                foreach (Texture2D texture in textures)
                {
                    ShowProgress((float)index / textures.Length, index, textures.Length);
                    index++;
                    string path = AssetDatabase.GetAssetPath(texture);
                    var textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                    if (!TextureTypeCompare(textureImporter.textureType)) continue;
                    var defaultSettings = textureImporter.GetPlatformTextureSettings(GetPlatformRealName((Platform)platform.value));
                    /* 原设置不覆盖设置,且当前设置为不强制覆盖,则跳过 */
                    if (!defaultSettings.overridden && !forceOverride.value) continue;
                    textureImporter.wrapMode = (TextureWrapMode)wrapMode.value;
                    textureImporter.filterMode = (FilterMode)filterMode.value;
                    textureImporter.anisoLevel = (int)anisoLevel.value;

                    var settings = new TextureImporterPlatformSettings()
                    {
                        name = defaultSettings.name,
                        resizeAlgorithm = (TextureResizeAlgorithm)resizeAlgorithm.value,
                        format = (TextureImporterFormat)format.value,
                        overridden = true,
                        maxTextureSize = (int)(MaxSize)maxSize.value,
                    };
                    textureImporter.SetPlatformTextureSettings(settings);
                    AssetDatabase.ImportAsset(path);
                }
                AssetDatabase.Refresh();
                EditorUtility.ClearProgressBar();
                /// <summary>
                /// true: 图片类型一致
                /// </summary>
                /// <param name="source"></param>
                /// <returns></returns>
                bool TextureTypeCompare(TextureImporterType source)
                {
                    return source == (TextureImporterType)textureType.value;
                }
            }
        }
        private StyleSheet GetStyleFile(string fileName)
        {
            return Resources.Load<StyleSheet>(fileName);
        }
        private VisualTreeAsset GetVisualTree(string fileName)
        {
            return Resources.Load<VisualTreeAsset>(fileName);
        }
        public static void ShowProgress(float progress, int current, int total)
        {
            EditorUtility.DisplayProgressBar("设置图片中...", $"进度: {current}/{total}", progress);
        }
        private string GetPlatformRealName(Platform platform)
        {
            var str = string.Empty;
            switch (platform)
            {
                case Platform.Standalone:
                    str = "Standalone";
                    break;
                case Platform.Web:
                    str = "Web";
                    break;
                case Platform.iPhone:
                    str = "iPhone";
                    break;
                case Platform.Android:
                    str = "Android";
                    break;
                case Platform.WebGL:
                    str = "WebGL";
                    break;
                case Platform.WindowsStoreApps:
                    str = "Windows Store Apps";
                    break;
                case Platform.PS4:
                    str = "PS4";
                    break;
                case Platform.PSM:
                    str = "PSM";
                    break;
                case Platform.XboxOne:
                    str = "XboxOne";
                    break;
                case Platform.Nintendo3DS:
                    str = "Nintendo 3DS";
                    break;
                case Platform.tvOS:
                    str = "tvOS";
                    break;
                default: throw new System.Exception($"找不到平台: {platform}");
            }
            return str;
        }
        #endregion


        #region static
        [MenuItem("Window/TextureSetting")]
        public static void Open()
        {
            if (Instance == null)
            {
                Instance = GetWindow<TextureSettingWindow>(false, "TextureSetting", true);
                Instance.minSize = new Vector2(600f, 400f);
                Instance.Init();
                Instance.Show();
                EditorPrefs.SetBool("texture setting open", true);
            }
            else Instance.Focus();
        }
        [UnityEditor.Callbacks.DidReloadScripts]
        private static void OnScriptReloaded()
        {
            if (EditorPrefs.GetBool("texture setting open", false)) Open();
        }
        public static TextureSettingWindow Instance;
        #endregion
    }
}